package com.gzhu.knowledgeAdmin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzhu.knowledgeAdmin.common.constant.OperatorType;
import com.gzhu.knowledgeAdmin.common.utils.StringUtils;
import com.gzhu.knowledgeAdmin.common.vo.ConditionVo;
import com.gzhu.knowledgeAdmin.common.vo.PageVo;
import com.gzhu.knowledgeAdmin.entity.Keyword;
import com.gzhu.knowledgeAdmin.entity.Operator;
import com.gzhu.knowledgeAdmin.service.KeywordService;
import com.gzhu.knowledgeAdmin.service.OperatorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.gzhu.knowledgeAdmin.dao.ConditionDao;
import com.gzhu.knowledgeAdmin.entity.Condition;
import com.gzhu.knowledgeAdmin.service.ConditionService;
import org.springframework.transaction.annotation.Transactional;


@Service("conditionService")
public class ConditionServiceImpl extends ServiceImpl<ConditionDao, Condition> implements ConditionService {

    @Autowired
    private OperatorService operatorService;

    @Autowired
    private KeywordService keywordService;

    @Override
    public PageVo queryPage(Map<String, Object> params) {
        // 获取当前页和每页大小
        long pageNo = Long.parseLong((String) params.get("page"));
        long pageSize = Long.parseLong((String) params.get("limit"));

        Page<Condition> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Condition> wrapper = new QueryWrapper<>();
        // TODO 根据params里的查询参数添加条件查询

        baseMapper.selectPage(page, wrapper);

        return new PageVo(page);
    }

    @Override
    @Transactional
    public ConditionVo saveOrUpdateCondtion(Condition condition) {

        // 1.插入
        saveOrUpdate(condition);


        return getConditionVo(condition);

    }

    private ConditionVo getConditionVo(Condition condition) {
        /**
         * 2.获取所有涉及到的算子
         */
        // 查出所有算子
        String content = condition.getContent();
        // 提取id
        List<Integer> ids = StringUtils.extractNumbers(content);
        // 所有涉及到的算子
        Collection<Operator> operators = operatorService.listByIds(ids);

        /**
         * 3.如果为包含关键字类型的算子，那么要将关键词id替换成关键词名称
         */
        // 获取所有涉及到的关键词，并封装成一个map<id,关键词>
        HashSet<Integer> keywordIdsSet = new HashSet<>();
        for (Operator operator : operators) {
            if (operator.getType() == OperatorType.CONTAIN_KEYWORD) {
                String[] split = operator.getContent().split(",");
                for (String s : split) {
                    keywordIdsSet.add(Integer.parseInt(s));
                }
            }
        }

        // 存在再操作
        if(!keywordIdsSet.isEmpty()){
            Collection<Keyword> keywords = keywordService.listByIds(keywordIdsSet);
            Map<Integer, String> keywordMap = keywords.stream().collect(Collectors.toMap(Keyword::getId, Keyword::getName));
            // 替换算子中关键词类型记录的content的id为对应名称
            for (Operator operator : operators) {
                if (operator.getType() == OperatorType.CONTAIN_KEYWORD) {

                    String operatorContent = operator.getContent();
                    String[] split = operatorContent.split(",");

                    StringBuilder stringBuilder = new StringBuilder();
                    for (String keywordId : split) {
                        Integer id = Integer.parseInt(keywordId);
                        stringBuilder.append(keywordMap.getOrDefault(id, keywordId));
                        stringBuilder.append(",");
                    }
                    // 移除最后一个多余的逗号
                    if (stringBuilder.length() > 0) {
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    }
                    operator.setContent(stringBuilder.toString());
                }
            }

        }


        List<Operator> operatorsList = new ArrayList<>(operators);
        // 4.将content中的id替换成编号
        Map<Integer, Integer> idMap = operatorsList.stream().collect(Collectors.toMap(Operator::getId, operator -> operatorsList.indexOf(operator) + 1));
        content = StringUtils.replaceIds(content, idMap);


        // 设置修改后的结果
        condition.setContent(content);
        // 5.封装结果
        ConditionVo conditionVo = new ConditionVo();
        BeanUtils.copyProperties(condition, conditionVo);
        conditionVo.setOperatorList(operatorsList);

        return conditionVo;
    }

    @Override
    public ConditionVo getConditionById(Integer id) {

        Condition condition = getById(id);

        // 获取该条件涉及到的所有算子
        return getConditionVo(condition);
    }

    @Override
    @Transactional
    public void removeConditionByIds(List<Integer> ids) {

        Collection<Condition> conditions = listByIds(ids);

        HashSet<Integer> operationIds = new HashSet<>();
        for (Condition condition : conditions) {
            operationIds.addAll(StringUtils.extractNumbers(condition.getContent()));
        }
        // 先删除涉及到的所有算子
        operatorService.removeByIds(operationIds);

        // 再删除条件
        removeByIds(ids);


    }



}